package com.fhz.a1911;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    private Button btn;
    private TextView tv;
    private static final String TAG = "feng";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //添加一个注释

        btn = (Button) findViewById(R.id.btn);
        tv = (TextView) findViewById(R.id.tv);

        //老方式
//        if(savedInstanceState != null){
//            String key = savedInstanceState.getString("key");
//            tv.setText(key);
//        }


        MyViewModel myViewModel = new ViewModelProvider(this,new MyViewModelFactory()).get(MyViewModel.class);
//        int index = myViewModel.getIndex();
//        tv.setText(myViewModel.getIndex()+"");
//        myViewModel.setIndex(number);

        myViewModel.getMutableLiveDataIndex().observe(this, new Observer<Integer>() {
            @Override
            public void onChanged(Integer integer) {
                tv.setText(integer+"");
            }
        });


        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //第一种
//                String s = tv.getText().toString();
//                tv.setText(Integer.parseInt(s)+1+"");
                //第二种
//                myViewModel.setIndex(myViewModel.getIndex()+1);
//                tv.setText(myViewModel.getIndex()+"");
                //第三种,用viewmodel和livedata结合的方法
                String s = tv.getText().toString();
                myViewModel.setIndex(Integer.parseInt(s)+1);
            }
        });


        Log.i(TAG, "onCreate: ");
    }



    @Override
    protected void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);
        //老方式
//        String s = tv.getText().toString();
//        outState.putString("key",s);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.i(TAG, "onDestroy: ");
    }

    @Override
    protected void onStop() {
        super.onStop();
        //
        SharedPreferences fen = getSharedPreferences("fen", MODE_PRIVATE);
        fen.edit().putInt("number",Integer.parseInt(tv.getText().toString())).apply();

    }
}